package com.tech.koufu.ui.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MainActivity;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.model.StockInfo;
import com.tech.koufu.model.UserStocks;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.HttpUtils;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.view.ChooseStockFragment;
import com.tech.koufu.ui.view.MainContentFragment;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
/**
 * 购买股票 买入界面 和卖出股票页面通用
 */
public class BuyStocksActivity extends Activity implements View.OnClickListener{
	private Context mContext;
	/**
	 * 0为买入界面，1为卖出界面
	 */
	private int type = 0;
	private String mmlb = null;
	private Boolean BLMoney = false;
	private List<StockInfo> list = new ArrayList<StockInfo>();
	protected StockInfo info = new StockInfo();
	protected UserStocks mUserStocks;
	CookieStringRequest stringRequest;
	private RequestQueue mQueue;
	private Handler mHandler = new Handler();
	private ProgressBar pb_wait;
	private RadioGroup rgp_shares;
	private RadioButton rb_btn_halfshares,rb_btn_thridshares,rb_btn_fourthshares;
	private Button btn_buy;
	private Button btn_home,btn_buy_ag;
	private TextView input_can_buynum,input_latest_stockprice,input_highest_stockprice,
	input_harden_stockprice,input_minimum_stockprice,input_stop_stockprice,txt_used_funds;
	private TextView inputStockCodeValue;
	private MyApplication myApp;
	private String ZTJ,DTJ,currentCode,canbuy,currentName;
	private String userMoney;
	private String userSaleNum;
	private Float stockNewPrice;
	private EditText input_buy_stock_price_value,input_buy_stock_num_value;
	private LinearLayout layout_buy_stocks;
	private LinearLayout ly_return_home;

	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buy_stocks);
		myApp = (MyApplication)getApplicationContext();
		type = getIntent().getIntExtra("type", 0);
		mContext = this;
		initView();
		if(type == 0){
			getUserMoney();
		}else{ 
			btn_buy.setText(R.string.btn_sell_stock); 
			userSaleNum = mUserStocks.getStockHold();
			input_can_buynum.setText("可卖："+ userSaleNum);
			txt_used_funds.setText("持股数：" + userSaleNum); 
		}
		getStockInfo();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(mContext);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(mContext);
	}

	private void initView() { 
		pb_wait = (ProgressBar)findViewById(R.id.pb_wait);
		layout_buy_stocks = (LinearLayout)findViewById(R.id.layout_buy_stocks);
		ly_return_home = (LinearLayout)findViewById(R.id.ly_return_home);
		input_can_buynum = (TextView)findViewById(R.id.input_can_buynum);
		input_latest_stockprice = (TextView)findViewById(R.id.input_latest_stockprice);
		input_highest_stockprice = (TextView)findViewById(R.id.input_highest_stockprice);
		input_harden_stockprice = (TextView)findViewById(R.id.input_harden_stockprice);
		input_minimum_stockprice = (TextView)findViewById(R.id.input_minimum_stockprice);
		input_stop_stockprice = (TextView)findViewById(R.id.input_stop_stockprice);
		txt_used_funds = (TextView)findViewById(R.id.txt_used_funds);
		rb_btn_halfshares = (RadioButton)findViewById(R.id.rb_btn_halfshares);
		rb_btn_thridshares = (RadioButton)findViewById(R.id.rb_btn_thridshares);
		rb_btn_fourthshares = (RadioButton)findViewById(R.id.rb_btn_fourthshares);
		btn_buy = (Button)findViewById(R.id.btn_buy);
		btn_buy_ag = (Button)findViewById(R.id.btn_buy_ag);
		btn_home = (Button)findViewById(R.id.btn_home);
		btn_buy.setOnClickListener(this);
		btn_buy_ag.setOnClickListener(this);
		btn_home.setOnClickListener(this);
		ImageView btnRefresh = (ImageView)findViewById(R.id.btn_refresh); 
		btnRefresh.setOnClickListener(this);

		inputStockCodeValue = (TextView)findViewById(R.id.input_stock_code_value);
		inputStockCodeValue.setOnClickListener(this);
		input_buy_stock_price_value = (EditText)findViewById(R.id.input_buy_stock_price_value);
		input_buy_stock_num_value = (EditText)findViewById(R.id.input_buy_stock_num_value);

		mQueue = Volley.newRequestQueue(getApplicationContext());
		int parseType = getIntent().getIntExtra("parsetype", 0); 
		if(parseType ==0){
			mUserStocks = (UserStocks) getIntent().getSerializableExtra("stockInfo");
			currentCode = mUserStocks.getStockId().substring(1);
			currentName = mUserStocks.getStockName();
			inputStockCodeValue.setText("(" + currentCode + ")" + currentName);
			input_buy_stock_price_value.setText(mUserStocks.getStockdqj());

		}else if(parseType ==3){//搜索跳进来
			currentCode = getIntent().getStringExtra("code");
			currentName = getIntent().getStringExtra("name");
			inputStockCodeValue.setText("(" + currentCode + ")" + currentName);
		} else{
			info = getIntent().getParcelableExtra("stockInfo");
			currentCode = info.getCode();
			currentName = info.getName();
			inputStockCodeValue.setText("(" + currentCode + ")" + currentName);
			input_buy_stock_price_value.setText(info.getZx());
		}
		ImageView ivBack = (ImageView)findViewById(R.id.img_callback); 
		ivBack.setOnClickListener(this); 

		rgp_shares = (RadioGroup)findViewById(R.id.rgp_shares);
		rgp_shares.setOnCheckedChangeListener(new rgpOnCheckedChangeListener());
		TextView input_buy_stock_num = (TextView)findViewById(R.id.input_buy_stock_num);
		TextView txtTitle = (TextView)findViewById(R.id.tv_title); 
		if(type==0){
			mmlb = "r";
			txtTitle.setText(R.string.btn_buy_stock);
		}else{
			mmlb = "c";
			txtTitle.setText(R.string.btn_sell_stock);
			TextView input_buy_stock_price;
			input_buy_stock_price =(TextView)findViewById(R.id.input_buy_stock_price);
			input_buy_stock_price.setText(R.string.input_sell_stock_price);
			input_buy_stock_num.setText(R.string.input_sell_stock_num);
		}
	}

	@Override
	public void onClick(View v) { 
		switch (v.getId()) {
		case R.id.img_callback:
			this.finish();
			break;
		case R.id.btn_refresh:
			break;
		case R.id.btn_buy:
			String buyPrice = input_buy_stock_price_value.getText().toString();
			String buyNum = input_buy_stock_num_value.getText().toString();
			if(stockNewPrice != 0){
				if(type==0){
					if(!TextUtils.isEmpty(buyPrice) && !TextUtils.isEmpty(buyNum)){

						if(Integer.valueOf(buyNum)%100 != 0 || Integer.valueOf(buyNum) <= 0){
							Toast.makeText(getApplicationContext(), "买入数量必须为100的倍数", Toast.LENGTH_SHORT).show();
						}else if(!TextUtils.isEmpty(buyPrice)&& Integer.valueOf(buyNum)%100 == 0 
								&& Integer.valueOf(buyNum) > 0 &
								Float.parseFloat(buyPrice) < Float.parseFloat(ZTJ)){
							postWT();
						}else if(Float.parseFloat(buyPrice) >= Float.parseFloat(ZTJ)){
							Toast.makeText(getApplicationContext(), R.string.txt_buy_price, Toast.LENGTH_LONG).show();
						}
					}else{
						Toast.makeText(getApplicationContext(), "请正确输入买入信息！", Toast.LENGTH_SHORT).show();
					}
				}else{
					if(!TextUtils.isEmpty(buyPrice) && !TextUtils.isEmpty(buyNum)){
						if(Integer.valueOf(buyNum) > 0 && Float.parseFloat(buyPrice) > Float.parseFloat(DTJ) 
								&& Integer.valueOf(buyNum) <= Integer.valueOf(userSaleNum)){
							postWT();
						}else if(Float.parseFloat(buyPrice) <= Float.parseFloat(DTJ)){
							Toast.makeText(getApplicationContext(), R.string.txt_buy_price, Toast.LENGTH_LONG).show();
						}else if(Integer.valueOf(buyNum) > Integer.valueOf(userSaleNum) && !userSaleNum.equals("0")){
							Toast.makeText(getApplicationContext(), "卖出数量超过持股数量！", Toast.LENGTH_SHORT).show();
						}else if(userSaleNum.equals("0")){
							Toast.makeText(getApplicationContext(), "当天买入的股票不能进行委托！", Toast.LENGTH_SHORT).show();
						}else{
							Toast.makeText(getApplicationContext(), "请正确输入卖出数量！", Toast.LENGTH_SHORT).show();
						}
					}else{
						Toast.makeText(getApplicationContext(), "请正确输入卖出信息！", Toast.LENGTH_SHORT).show();
					}
				}
			}else{
				Toast.makeText(getApplication(), "该股票当前停牌，不可买卖！",Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.btn_buy_ag:
			ly_return_home.setVisibility(View.GONE);
			btn_buy.setVisibility(View.VISIBLE);
			break;
		case R.id.btn_home:
			Intent intent = new Intent(this,MainActivity.class);
			startActivity(intent);
			break;
		case R.id.input_stock_code_value:
			if(type == 0){
				Intent intent1 = new Intent(this,ChooseStockFragment.class);
				intent1.putExtra("userStock", myApp.mUserStocks);
				startActivity(intent1);
			}else{
				Intent intent1 = new Intent(this,SellStocksListActivity.class);
				intent1.putExtra("userStock", myApp.mUserStocks);
				startActivity(intent1);
			}
		default:
			break;
		}
	}

	private void getZTJ(){
		String zqlb = KouFuTools.stockGetZQLB(Integer.valueOf(info.getCode()), info.getName());
		if(info.getName().contains("N")){
			DecimalFormat decimalFormat=new DecimalFormat(".00");
			ZTJ = "" + decimalFormat.format(Float.parseFloat(info.getZsp())*(1+44f/100));
			DTJ = "0";
		}else if(info.getName().contains("ST")){
			DecimalFormat decimalFormat=new DecimalFormat(".00");
			ZTJ = "" + decimalFormat.format(Float.parseFloat(info.getZsp())*(1+5f/100));
			DTJ = "" + decimalFormat.format(Float.parseFloat(info.getZsp())*(1-5f/100));
		}else if(zqlb == "F" || zqlb == "B" ||zqlb == "Z" || zqlb == "E"){
			DecimalFormat decimalFormat=new DecimalFormat(".000");
			ZTJ = "" + decimalFormat.format(Float.parseFloat(info.getZsp())*(1+10f/100));
			DTJ = "" + decimalFormat.format(Float.parseFloat(info.getZsp())*(1-10f/100));
		}else{
			DecimalFormat decimalFormat=new DecimalFormat(".00");
			ZTJ = "" + decimalFormat.format(Float.parseFloat(info.getZsp())*(1+10f/100));
			DTJ = "" + decimalFormat.format(Float.parseFloat(info.getZsp())*(1-10f/100));
		}
	}

	private void getUserMoney(){
		new Thread(new Runnable() {

			@Override
			public void run() {
				String t = KouFuTools.readTimeInfo(new String());
				Map<String,String> data = new HashMap<String, String>();
				data.put("userid",myApp.getGroupId() + "X" +myApp.getDigitalid());
				data.put("compress", "1");
				data.put("time",t);
				String cookie = KouFuTools.descrypt(myApp.getGroupId() + "X" +myApp.getDigitalid()+t);
				String money = HttpUtils.postRequest(myApp.url+"Money.dll", cookie, data);				
				Log.v("UserMoney", money);
				BLMoney = true; 
				if(money==null)
					return;
				String status = money.substring(0,1);
				if(status.equals("1")){
					return;
				}
				userMoney = money.substring(money.indexOf(":")+1, money.indexOf(",")); 
				mHandler.post(new Runnable() {

					@Override
					public void run() { 
						txt_used_funds.setText("可用资金：" + userMoney); 
						//						BLMoney = true; 
						//						canBuy() ; 
					}
				});
			}
		}).start();
	}
	private void getStockInfo(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String returnValue = HttpUtils.getRequest(myApp.url + "BinStock.dll?stock="+KouFuTools.getNcode(currentCode)
						+"&field=ZSP,JKP,CJE,ZG,ZD,ZX,BJ1,SJ1,CJL,SYL," +
						"BL1,BJ2,BL2,BJ3,BL3,SL1,SJ2,SL2,SJ3,SL3,BJ4,BL4,BJ5,BL5,SJ4,SL4,SJ5,SL5");//1600879
				Log.v("BuyStock==>", returnValue);
				String[] a = returnValue.trim().split(",");
				Log.v("StringA=!!",String.valueOf(a.length));
				info.setCode(a[0].toString().trim());
				info.setName(a[1].toString().trim());
				info.setZsp(a[2].toString().trim());
				info.setJkp(a[3].toString().trim());
				info.setCje(a[4].toString().trim());
				info.setZg(a[5].toString().trim());
				info.setZd(a[6].toString().trim());
				info.setZx(a[7].toString().trim());
				info.setBj1(a[8].toString().trim());
				info.setSj1(a[9].toString().trim());
				info.setCjl(a[10].toString().trim());
				info.setSyl(a[11].toString().trim());
				info.setBl1(a[12].toString().trim());
				info.setBj2(a[13].toString().trim());
				info.setBl2(a[14].toString().trim());
				info.setBj3(a[15].toString().trim());
				info.setBl3(a[16].toString().trim());
				info.setSl1(a[17].toString().trim());
				info.setSj2(a[18].toString().trim());
				info.setSl2(a[19].toString().trim());
				info.setSj3(a[20].toString().trim());
				info.setSl3(a[21].toString().trim());
				info.setBj4(a[22].toString().trim());
				info.setBl5(a[23].toString().trim());
				info.setBj5(a[24].toString().trim());
				info.setBl5(a[25].toString().trim());
				info.setSj4(a[26].toString().trim());
				info.setSl4(a[27].toString().trim());
				info.setSj5(a[28].toString().trim());
				info.setSl5(a[29].toString().trim());
				//				list.add(info);
				Log.v("BuyStocksActivity", info.toString());
				getZTJ();
				mHandler.post(new Runnable() { 
					@Override
					public void run() {
						stockNewPrice = Float.parseFloat(info.getZx());
						if(stockNewPrice == 0){
							Toast.makeText(getApplicationContext(), "该股票当前停牌！", Toast.LENGTH_SHORT).show();
							rb_btn_halfshares.setClickable(false);
							rb_btn_thridshares.setClickable(false);
							rb_btn_fourthshares.setClickable(false);
						}else{
							input_buy_stock_price_value.setText(String.valueOf(stockNewPrice));
							input_latest_stockprice.setText("最新：" + info.getZx());
							input_highest_stockprice.setText("最高：" + info.getZg());
							input_minimum_stockprice.setText("最低：" + info.getZd());
							input_harden_stockprice.setText("涨停价：" + ZTJ);
							input_stop_stockprice.setText("跌停价：" + DTJ);  
							if(type == 0 && Float.parseFloat(info.getZx()) != 0){
								do{
									canBuy();
								}while(!BLMoney && !info.getZx().equals("0"));
							}
						}
						pb_wait.setVisibility(View.GONE);
						layout_buy_stocks.setVisibility(View.VISIBLE);
						//						showContent();
					} 
				});
			}

		}).start();
	}

	private void canBuy() {
		if(userMoney!=null && info!=null &&!TextUtils.isEmpty(info.getZx())){ 
			Float can_buy = Float.parseFloat(userMoney)/Float.parseFloat(info.getZx());
			canbuy = String.valueOf(can_buy).substring(0, String.valueOf(can_buy).indexOf("."));
			input_can_buynum.setText("可买："+canbuy);
		}else{
			input_can_buynum.setText("可买：———");
		}
	} 

	private void postWT(){ 
		String url = myApp.url +Statics.Request_WT; 
		final String t = KouFuTools.readTimeInfo(new String());

		stringRequest = new CookieStringRequest(Request.Method.POST,url, new Response.Listener<String>() {

			@Override
			public void onResponse(String response) {
				// TODO Auto-generated method stub
				if(response!=null && !response.equals("")){
					String[] results = response.split(":");
					if(results[0].equals("0")){
						Toast.makeText(getApplicationContext(), results[1], Toast.LENGTH_SHORT).show();
						ly_return_home.setVisibility(View.VISIBLE);
						btn_buy.setVisibility(View.GONE);
						if (type == 0) {
							btn_buy_ag.setText("继续买入");
						}else{
							btn_buy_ag.setText("继续卖出");
						}
					}else if (results[0].equals("1")){
						//1:您没有该股票或者卖出数量超出了可卖数，如有异议，请与管理员联系。 
						Toast.makeText(getApplicationContext(), results[1], Toast.LENGTH_SHORT).show();
					}
					Log.d("WTsuccess!!", "~~~~~~~~~~response~~~~~");
					Log.v("WTsuccess!!", response.toString());
				}
			}

		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub
				Log.e("Tt", error.getMessage());
			}

		}){
			@Override
			protected Map<String, String> getParams()
					throws AuthFailureError {    
				Map<String, String> params = new HashMap<String, String>();
				params.put("userid", myApp.getUserid());
				params.put("username", myApp.getUserName());
				params.put("teamid", myApp.getTeamid());  
				params.put("time", t);
				//msg：委托信息，格式：mmlb,stockcode,stockname,stocktype,zqlb,price,amount
				String sid = info.getCode();
				String sN = info.getName();
				String msg = new StringBuilder(mmlb).append(",")
						.append(sid).append(",")
						.append(sN).append(",")
						.append(KouFuTools.getEnCode(sid)).append(",")
						.append(KouFuTools.stockGetZQLB(Integer.parseInt(sid),sN)).append(",")
						.append(input_buy_stock_price_value.getText()).append(",")
						.append(input_buy_stock_num_value.getText())
						.toString();
				byte[] bytemsg = hexStringToByte(msg);
				Log.d("16=======！！！" , Arrays.toString(bytemsg));
				params.put("msg", msg);
				Log.d("BuyWT", "~~~~~~~~msg==" + msg);
				Log.d("BuyWT", "~~~~~~~~url==" + params);
				return params;
			}

		}; 
		String cookie = KouFuTools.descrypt(myApp.getUserid()+t);
		stringRequest.setHeader(cookie);
		stringRequest.setCharset("GBK");
		stringRequest.setRequestCharset("GBK"); 
		mQueue.add(stringRequest);
	} 

	public static byte[] hexStringToByte(String hex) {   
		int len = (hex.length() / 2);   
		byte[] result = new byte[len];   
		char[] achar = hex.toCharArray();   
		for (int i = 0; i < len; i++) {   
			int pos = i * 2;   
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));   
		}   
		return result;   
	}  

	private static byte toByte(char c) {   
		byte b = (byte) "0123456789ABCDEF".indexOf(c);   
		return b;   
	}  
	private class rgpOnCheckedChangeListener implements OnCheckedChangeListener{
		String halfnum;
		String newhalfnum;
		@Override
		public void onCheckedChanged(RadioGroup arg0, int arg1) { 
			switch (arg0.getCheckedRadioButtonId()) {
			case R.id.rb_btn_halfshares:
				if(type == 0){
					halfnum = ""+((Integer.valueOf(canbuy)/2));
					newhalfnum = ""+(Integer.valueOf(halfnum)-(Integer.valueOf(halfnum)%100));
					input_buy_stock_num_value.setText(newhalfnum);
				}else{
					halfnum = ""+(Integer.valueOf(userSaleNum)/2);
					input_buy_stock_num_value.setText(halfnum);
				}
				break;
			case R.id.rb_btn_thridshares:
				if(type == 0){
					halfnum = ""+((Integer.valueOf(canbuy)/3));
					newhalfnum = ""+(Integer.valueOf(halfnum)-(Integer.valueOf(halfnum)%100));
					input_buy_stock_num_value.setText(newhalfnum);
				}else {
					halfnum = ""+(Integer.valueOf(userSaleNum)/3);
					input_buy_stock_num_value.setText(halfnum);
				}
				break;
			case R.id.rb_btn_fourthshares:
				if(type == 0){
					halfnum = ""+(Integer.valueOf(canbuy)%100);
					input_buy_stock_num_value.setText(""+(Integer.valueOf(canbuy)-Integer.valueOf(halfnum)));
				}else{
					input_buy_stock_num_value.setText(userSaleNum);
				}
				break;
			default:
				break;				
			}			
		}		
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			this.finish();
			clear();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void clear(){
		if(stringRequest != null){
			mQueue.cancelAll(stringRequest);
		}		
	}
}
